<template>
  <div class="login">
    <el-form
      ref="loginFormRef"
      label-width="120px"
      class="loginForm"
      status-icon
      :model="loginForm"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button @click="login(loginFormRef)" type="primary"> 登录 </el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
//引入封装好的接口
import {userLogin} from '../request/api'
import { reactive,ref } from "vue";
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
//自定义类型引入
import type { FormRules,FormInstance } from "element-plus";
import {ElMessage} from 'element-plus'
//定义路由控制器
let router = useRouter()
let store = useStore()
// console.log(router,'路由控制器')
//定义form表单节点
let loginFormRef = ref<FormInstance>()
let loginForm = reactive({
  username: "",
  password: "",
});
let rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 8, message: "长度2-8之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度6-16之间", trigger: "blur" },
  ],
});
//封装一个登录事件
let login = (formEl:FormInstance|undefined) => {
    if(formEl){
        formEl.validate((val)=>{
            console.log(val,'判断的状态')
            if(val){
                //console.log(loginForm, "表单对象");
                //跳转到index界面
                // router.push('/index')
                //调用登录接口
                userLogin(loginForm)
                .then((res:any)=>{
                  if(res.data.code==200){
                    ElMessage.success(res.data.msg)
                    //注意： 先存储后跳转
                    store.dispatch('changeUserAction',res.data.list)
                    router.push('/index')
                  }else{
                    ElMessage.error(res.data.msg)
                  }
                })
            }
        })
    }else{

    }
  
};
</script>

<style lang="less" scoped>
.login {
  width: 100vw;
  height: 100vh;
  .loginForm {
    position: absolute;
    width: 400px;
    height: 350px;
    top: 50%;
    left: 50%;
    margin: -175px 0 0 -150px;
  }
}
</style>
